using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO.ClassDefinition;

namespace FireStarterModeller.Logic
{
    /// <summary>
    /// Creates an Entity Based On a <see cref="DMClass"/>
    /// </summary>
    public static class DMClassEntityCreator
    {
        /// <summary>
        /// Creatss a Solution with all the standard Control Types, Control mapper types and Property Types.
        /// </summary>
        public static Entity CreateEntity(DMClass dmClass, ClassDefCol classDefs)
        {
            IClassDef classDef = classDefs["FirestarterModeller.BO", "Entity_" + dmClass.ClassNameBO];
            Entity entity = CreateEntity(classDef);
            entity.DMClassID = dmClass.ClassID;
            return entity;
        }

        public static Entity CreateEntity(IClassDef classDef)
        {
            Entity entity = new Entity(classDef);

            //This is required because an Entity that is defined with a
            // primary key has the primary key removed and replaced with the
            // EntityID as the primary key when the ClassDefs are created for the 
            // Entity.
            // A track of the origionally modelled primary key is kept as an
            // alternate key named DomainPrimaryKey.
            // If this domain primary key is a Guid and there is only one i.e. it was an object ID
            // then the New Entity's EntityID should be the same as this Modelled ID.
            KeyDef def = FindKeyDef(classDef, "DomainPrimaryKey");
            if (def == null || def.Count != 1) return entity;
            IPropDef propDef = def[0];
            if (propDef.PropertyTypeName == "System.Guid")
            {
                entity.SetPropertyValue(propDef.PropertyName, entity.EntityID);
            }
            return entity;
        }

        private static KeyDef FindKeyDef(IClassDef classDef, string keyName)
        {
            foreach (KeyDef keyDef in classDef.KeysCol)
            {
                if (keyDef.KeyName == keyName || keyDef.KeyName.StartsWith(keyName + "_"))
                {
                    return keyDef;
                }
            }
            return null;
        }
    }
}